package dao;

import java.math.BigDecimal;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import to.Address;
import util.ConnectionUtil;

public class AddressDao {

    public long addAddress(String city) {
        long id = getAddressId();
        if (id == -1) {
            return id;
        }

        Address address = new Address(city);
        address.setId(id);
        SessionFactory sessionFactory = ConnectionUtil.getSessionFactory();
        Session session = null;
        Transaction transaction = null;
        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();
            id = (long) session.save(address);
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
            id = -1;
            if (transaction != null) {
                transaction.rollback();
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return id;
    }

    private long getAddressId() {
        String sql = "select seq_my_address.nextval from dual";
        SessionFactory sessionFactory = ConnectionUtil.getSessionFactory();
        Session session = null;
        long id = -1;
        try {
            session = sessionFactory.openSession();
            BigDecimal bigDecimal = (BigDecimal) session.createSQLQuery(sql).list().get(0);
            id = bigDecimal.longValue();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return id;
    }
}
